import React, { useReducer } from "react";

const reducer  = (state, action) => {
    const {type, payload} = action
    switch(type){
      case 'increment':
        return {...state, age:state.age + 1}
      case 'decrement':
        return {...state, age: state.age -1}
      case 'changeUser':
        return {...payload}
      default:
        return state
    }
}

const initalUser = {
  id: '001',
  name: 'xia',
  age: 27
}
export const ReducerDemo = () => {
  const [state, dispatch] = useReducer(reducer, initalUser)
  return (
    <div>
      <div>用户名:{state.name}, 年龄: {state.age}</div>
      <button onClick={() => dispatch({type:'increment',paylod: 1 })}>成熟</button>
      <button onClick={() => dispatch({type:'decrement',paylod: -1 })}>稚嫩</button>
      <button onClick={() => dispatch({type:'changeUser', payload:{id:'002', name:'Tom', age:18}})}>切换用户</button>
    </div>
  )
}